#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project : tools-for-internet-security
@File : encryption_decryption.py
@Author : Hunter, Misha
@Time : 2025/5/11 17:47
@脚本说明 : 文件加密
"""
from Crypto.Cipher import AES
import os


def encrypt_file(file_path):
    key = b"HackerMisha66666"
    with open(file=file_path, mode="rb") as f:
        data = f.read()
    # 创建加密器（使用CBC模式）
    cipher = AES.new(key, AES.MODE_CBC)
    # 填充数据使其长度为16的倍数
    pad_len = AES.block_size - len(data) % AES.block_size
    data += bytes([pad_len]) * pad_len
    # 加密数据
    encrypted_data = cipher.iv + cipher.encrypt(data)
    # 写入加密文件
    encrypted_path = os.path.abspath(file_path) + '.sec'
    with open(encrypted_path, 'wb') as f:
        f.write(encrypted_data)
    os.remove(file_path)
    print("文件已加密！")


def decrypt_file(file_path):
    key = b"HackerMisha66666"
    if os.path.splitext(file_path)[1] == '.sec':
        output_path = os.path.splitext(os.path.abspath(file_path))[0]
    else:
        print("不是用本软件加密的文件可能无法解密！")
        output_path = os.path.abspath(file_path)
    # 读取加密文件
    with open(file_path, 'rb') as f:
        encrypted_data = f.read()
    try:
        # 提取IV（初始向量）
        iv = encrypted_data[:AES.block_size]
        cipher = AES.new(key, AES.MODE_CBC, iv=iv)
        # 解密数据
        decrypted_data = cipher.decrypt(encrypted_data[AES.block_size:])
        # 去除填充
        pad_len = decrypted_data[-1]
        decrypted_data = decrypted_data[:-pad_len]
        # 写入解密文件
        with open(output_path, 'wb') as f:
            f.write(decrypted_data)
        print("文件已解密！")
        if os.path.abspath(file_path) != output_path:
            os.remove(file_path)
    except Exception as e:
        print(f"解密失败！{type(e)}:{e}")


if __name__ == '__main__':
    # encrypt_file("D:/ResourceHacker_5.2.8.43_CHS.exe")
    decrypt_file("D:/ResourceHacker_5.2.8.43_CHS.exe.sec")
